package com.es.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 描述:
 * es-meta-
 *
 * @author Derek
 * @create 2021-11-30 9:54
 */
@Configuration
@ComponentScan(basePackages = {"com.es"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {EnableWebMvc.class, Controller.class})})
@EnableTransactionManagement
@MapperScan(basePackages = {"com.es.mapper"})
@PropertySource("classpath:jdbc.properties")
public class RootApplicationContextConfig {

    @Value("${jdbc.driver}")
    private String driverClassName;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Autowired
    private DataSource dataSource;


    @Bean
    public DataSource dataSource(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        //
        dataSource.setMaximumPoolSize(50);
        dataSource.setMinimumIdle(10);
        dataSource.setConnectionTimeout(50000);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(){
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        try {
            Properties properties = new Properties();
            properties.setProperty("logImpl","STDOUT_LOGGING");
            //配置
            sessionFactoryBean.setConfigurationProperties(properties);
            //别名
            sessionFactoryBean.setTypeAliasesPackage("com.es.entity");
            sessionFactoryBean.setDataSource(dataSource);
            return sessionFactoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Bean
    public DataSourceTransactionManager txManager(){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
